package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.union.cross.CrossUnionModule;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Protocol.S_UNION_KICK_PLAYER, desc = "踢出联盟")
public class KickPlayerCmd extends AbstractCommand {

	private long kickUserId;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		UnionProto.UnionKickPlayerReqMsg reqMsg = UnionProto.UnionKickPlayerReqMsg.parseFrom(packet.getBytes());
		kickUserId = reqMsg.getUserId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(player.getUserId() == kickUserId){
			ret = GameErrorCode.E_UNION_NO_KICK_SELF;
			return;
		}
		// 判断权限 族长 副族长才有权限
		String unionUid = player.getUserInfo().getUnionUid();
		if(StringUtils.isNullOrEmpty(unionUid)){
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		CrossUnionMember member = CrossUnionMgr.getUnionMember(unionUid, player.getUserId());
		if(null == member){
			ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
			return;
		}
		if (member.getPosition() == eUnionPosition.Master.getValue() || member.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
			// 判断副族长踢副族长
			if (member.getPosition() == eUnionPosition.DeputyMaster.getValue()) {
				UnionMember kickMember = CrossUnionMgr.getUnionMember(unionUid, kickUserId);
				if (kickMember != null) {
					if (kickMember.getPosition() == eUnionPosition.DeputyMaster.getValue() || kickMember.getPosition() == eUnionPosition.Master.getValue()) {
						ret = GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
						return;
					}
				}
			}

			ret = player.getModule(CrossUnionModule.class).canQuitUnion();

			if(ret == 0) {
				player.sendPacket(Protocol.C_UNION_KICK_PLAYER, UnionProto.UnionKickPlayerReqMsg.newBuilder().setUserId(kickUserId));
			}

		} else {
			ret = GameErrorCode.E_UNION_POSITION_NO_ENOUGH;
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		if(ret != 0) {
			UnionProto.UnionQuitRespMsg.Builder respMsg = UnionProto.UnionQuitRespMsg.newBuilder();
			respMsg.setRet(ret);
			player.sendPacket(Protocol.U_UNION_KICK_PLAYER, respMsg);
		}
	}

}
